package com.wpzf.zxhc.service.impl;

import com.alibaba.fastjson.JSON;
import com.wpzf.common.core.utils.StringUtils;
import com.wpzf.common.core.utils.sign.Base64;
import com.wpzf.zxhc.utils.MyStringUtils;
import com.wpzf.zxhc.domain.WpCjDkxxb2023DTO;
import com.wpzf.zxhc.domain.WpCjTbhcjg2023DTO;
import com.wpzf.zxhc.domain.WpCjTbjt2023DTO;
import com.wpzf.zxhc.domain.WpCjTbxxb2023DTO;
import com.wpzf.zxhc.mapper.WpzfTbBaseMapper;
import com.wpzf.zxhc.service.WpzfTbBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class WpzfTbBaseServiceImpl implements WpzfTbBaseService {

    @Autowired
    WpzfTbBaseMapper wpzftbbaseMapper;

    @Override
    public List<Map<String, Object>> queryUserByTasks(Map<String, Object> parm) {
        return wpzftbbaseMapper.queryUserByTasks(parm);
    }

    @Override
    public List<Map<String, Object>> queryByTask(Map<String, Object> parm) {
        return wpzftbbaseMapper.queryByTask(parm);
    }

    @Override
    public Map<String, Object> queryUserByHctbId(Map<String, Object> parm) {
        return wpzftbbaseMapper.queryUserByHctbId(parm);
    }

    @Override
    public WpCjDkxxb2023DTO querydkxxBytbbh(Map<String, Object> parm) {
        return wpzftbbaseMapper.querydkxxBytbbh(parm);
    }


    @Override
    public List<WpCjTbxxb2023DTO> querytbxxBytbbh(Map<String, Object> parm) {
        return wpzftbbaseMapper.querytbxxBytbbh(parm);
    }


    @Override
    public List<WpCjDkxxb2023DTO> querydkxxrelateBytbbh(Map<String, Object> parm) {
        String tbbh = parm.get("tbbh") + "";
        String jcbh = tbbh.split("-")[0];
        parm.put("jcbh", jcbh);
        return wpzftbbaseMapper.getCftbList(parm);
    }

    @Override
    public ModelMap getShowImgs(Map<String, Object> parms) {
        ModelMap map = new ModelMap();
        try {
            String tbbhs = parms.get("tbbh") + "";
            String xzqdm = parms.get("xzqdm") + "";
            String pch = parms.get("pch") + "";
            String postURL = "";
            String data = "";
            String strXzqdm = parms.get("xzqdm").toString().substring(0, 2);
            {
                postURL = "https://jg.landcloud.org.cn:8553/webapi/token";
                data = "client_id=web&client_secret=e46232c20609435eba54b7576de935dd&grant_type=password&username=a53e0c14ee900728f36bba014d975982&password=b30c775c48e9ba92ade95e427a5242b0";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            //关闭流
            is.close();

            conn.disconnect();
            String result = new String(datas, 0, datas.length, "utf-8");
            List<String> items = new ArrayList<>();
            {
                String t = getImg(result, tbbhs, xzqdm);
                items.add(t);
                map.put("data", items);
            }
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return map;
    }

    @Override
    public List<WpCjTbjt2023DTO> querytbjtBytbbh(Map<String, Object> parm) {
        String tbbh = parm.get("tbbh").toString();
        String xzqdm = parm.get("xzqdm").toString();
        String pch = parm.get("pch").toString();
        String url = "";
        String yf = "";
        if ("上半年-农房".equals(pch)) {
            yf = "上半年";
        } else if (pch != null && pch.length() != 0) {
            yf = pch;
        }
        String xzq = parm.get("xzqdm").toString().substring(0, 2);
        String dkbh = MyStringUtils.truncateString(tbbh);
        List<WpCjTbjt2023DTO> lists = new ArrayList<>();
        WpCjTbjt2023DTO model = new WpCjTbjt2023DTO();
        model.setName("用地管理信息套合示意图");
        url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2023/" + yf + "/" + xzq + "/" + xzqdm + "/" + xzqdm + "_" + dkbh + "_TBYD.jpg";
        model.setUrl(url);
        lists.add(model);

        model = new WpCjTbjt2023DTO();
        model.setName("自录批文示意图");
        url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2023/" + yf + "/" + xzq + "/" + xzqdm + "/" + xzqdm + "_" + dkbh + "_TBZLPW.jpg";
        model.setUrl(url);
        lists.add(model);

        model = new WpCjTbjt2023DTO();
        model.setName("耕地套合示意图");
        url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2023/" + yf + "/" + xzq + "/" + xzqdm + "/" + xzqdm + "_" + dkbh + "_GD.jpg";
        model.setUrl(url);
        lists.add(model);




        model = new WpCjTbjt2023DTO();
        model.setName("设施、临时用地备案示意图");
        url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2023/" + yf + "/" + xzq + "/" + xzqdm + "/" + xzqdm + "_" + dkbh + "_LSYDSSNYD.jpg";
        model.setUrl(url);
        lists.add(model);

        //重新获取批次号 wpzftbbaseMapper
        Map<String, Object> map = wpzftbbaseMapper.getoldpch(parm);
        String oldpch = "";
        if (map != null) {
            oldpch = map.get("pch").toString();
            if ("上半年-农房".equals(oldpch)) {
                oldpch = "上半年";
            } else if (oldpch != null && oldpch.length() != 0) {
                oldpch = oldpch;
            }
            model = new WpCjTbjt2023DTO();
            model.setName("初次-自录批文示意图");
            url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2023/" + oldpch + "/" + xzq + "/" + xzqdm + "/" + xzqdm + "_" + dkbh + "_LSYDSSNYD.jpg";
            model.setUrl(url);
            lists.add(model);
        }


        return lists;
    }
    public String getImg(String str, String xmbh, String xzqdm) {
        String rest = "";
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            String strXzqdm = xzqdm.substring(0, 2);
            Map mapType = JSON.parseObject(str, Map.class);
            {
                //  Map mapType = JSON.parseObject(str, Map.class);
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://jg.landcloud.org.cn:8553/webapi/api/nyhc/GetTBDetail";
            }


            URL url = new URL(postURL);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //请求方式
            conn.setRequestMethod("POST");
            //设置通用的请求属性
            String encoding = Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            //  out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据


            if (StringUtils.isNotBlank(xmbh)) {

                String data = "{\"xmbh\":[\"" + xmbh + "\"],\"xzqdm\":\"" + xzqdm + "\"}";
                System.out.println("---------3232------" + data);
                out.write(data);
                //缓冲数据
                out.flush();
                //获取URLConnection对象对应的输入流
                InputStream is = conn.getInputStream();

                int count = 0;

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                byte[] buffer = new byte[4096];

                while ((count = is.read(buffer)) != -1) {

                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
                System.out.println(rest);
                //writeLog(UtilTool.GetTime_1()+"：结束请求举证照片接口\n");
            }

        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            //writeLog(UtilTool.GetTime_1()+"："+e.getMessage()+"\n");
            throw new RuntimeException(e.getMessage());
        }
        return rest;
    }
}

